<?php

namespace wap\models;

use ijony\helpers\Image;
use ijony\helpers\Url;
use Yii;

/**
 * This is the model class for table "{{%cases}}".
 *
 * @property string $id 案例 ID
 * @property string $name 名称
 * @property string $preview 主图
 * @property string $developer 开发商
 * @property string $age 年代
 * @property string $description 简介
 * @property int $created_at 创建时间
 * @property int $updated_at 修改时间
 * @property int $status 状态
 *
 * @property \wap\models\Cases[] $cases
 * @property \wap\models\Products $product
 * @property \wap\models\Products[] $products
 * @property \wap\models\CaseGalleries[] $gallery
 */
class Cases extends \common\models\Cases
{

    public function getCases()
    {
        $product_ids = CaseProducts::find()->select('product_id')->where(['case_id' => $this->id])->column();
        $case_ids = CaseProducts::find()->select('case_id')->where([
            'and',
            ['in', 'product_id', $product_ids],
            ['<>', 'case_id', $this->id],
        ])->column();

        return Cases::find()->where(['id' => $case_ids])->all();
    }

    public function getProduct()
    {
        return $this->hasOne(Products::className(), ['id' => 'product_id'])->alias('product')->viaTable(CaseProducts::tableName(), ['case_id' => 'id']);
    }

    public function getProducts()
    {
        return $this->hasMany(Products::className(), ['id' => 'product_id'])->alias('product')->viaTable(CaseProducts::tableName(), ['case_id' => 'id']);
    }

    public function getGallery()
    {
        return $this->hasMany(CaseGalleries::className(), ['case_id' => 'id']);
    }

    public function getViewUrl()
    {
        return Url::to(['case/view', 'id' => $this->id]);
    }

    public function getPreviewUrl($width = 0, $height = 0, $cut = true)
    {
        return Image::getImg($this->preview, $width, $height, true, $cut ? Image::THUMB_MODE_CUT : Image::THUMB_MODE_ADAPT);
    }

    public function getOutside()
    {
        $product = $this->getProduct()->one();

        return $product->name;
    }

    public static function getNavs()
    {
        $return[] = [
            'url' => Url::to(['case/index']),
            'name' => '项目时间',
            'active' => true,
            'childs' => self::getAgeChild(),
        ];

        return $return;
    }

    public static function getAgeChild()
    {
        $ageInput = Yii::$app->request->getQueryParam('age');
        $ages = self::find()->select('age')->groupBy('age')->orderBy(['age' => SORT_DESC])->column();

        return array_map(function($age)use($ageInput){
            return [
                'url' => Url::to(['case/index', 'age' => $age]),
                'name' => $age,
                'active' => $age == $ageInput ? 'active' : '',
            ];
        }, $ages);
    }
}
